/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

import entity.Account;
import entity.AccountFacadeLocal;
import entity.Moneytransferlog;
import entity.MoneytransferlogFacadeLocal;
import entity.MoneytransferlogPK;
import java.util.Date;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

/**
 *
 * @author Thai Dac Vinh
 */
@Stateless
public class AccountService implements AccountServiceLocal {

    @EJB AccountFacadeLocal accountFacadeLocal;
    @EJB MoneytransferlogFacadeLocal moneytransferlogFacadeLocal;
    
    @Override
    @TransactionAttribute(TransactionAttributeType.NEVER)
    public int moneyTransfer(final String senderAID, final String receiverAID, final Date transferDate, final float amount, final String details) {
        return _moneyTransfer(senderAID, receiverAID, transferDate, amount, details);
    }

    @Override
    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public int moneyTransferSafely(final String senderAID, final String receiverAID, final Date transferDate, final float amount, final String details) {
        return _moneyTransfer(senderAID, receiverAID, transferDate, amount, details);
    }
    
    @TransactionAttribute(TransactionAttributeType.SUPPORTS)
    private int _moneyTransfer(final String senderAID, final String receiverAID, final Date transferDate, final float amount, final String details) {
        Account senderAccount = accountFacadeLocal.find(senderAID);
        Account receiverAccount = accountFacadeLocal.find(receiverAID);

        float senderBalance = senderAccount.getBalance();
        senderAccount.setBalance(senderBalance - amount);
        accountFacadeLocal.edit(senderAccount);

        float receiverBalance = receiverAccount.getBalance();
        receiverAccount.setBalance(receiverBalance + amount);
        accountFacadeLocal.edit(receiverAccount);

        MoneytransferlogPK moneyTransferLogPK = new MoneytransferlogPK(transferDate, senderAID, receiverAID);
        Moneytransferlog moneytransferlog = new Moneytransferlog();
        moneytransferlog.setMoneytransferlogPK(moneyTransferLogPK);
        moneytransferlog.setSenderAccount(senderAccount);
        moneytransferlog.setReceiverAccount(receiverAccount);
        moneytransferlog.setAmount(amount);
        moneytransferlog.setDetails(details);

        moneytransferlogFacadeLocal.create(moneytransferlog);

        return 0;
    }

}
